package com.showdor.dataSync;

import com.showdor.entity.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author showdor
 * @email chuanqi@outlook.com
 * @date 2025/2/21
 */
@Slf4j
public class DataSyncService {

    protected static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     *
     */
    Date initSyncTime(String lastSyncTimeFile) {
        Date lastSyncTime;
        //上次同步时间
        File file = new File(lastSyncTimeFile);
        if (!file.exists()) {
            try {
                file.createNewFile(); // 创建文件
                // 设置默认时间
                lastSyncTime = FORMATTER.parse("1970-01-01 00:00:00");
                // 写入默认时间
                saveLastSyncTime(lastSyncTime, lastSyncTimeFile);
                log.info("创建文件{}  time: {}", lastSyncTimeFile, FORMATTER.format(lastSyncTime));
            } catch (Exception e) {
                log.error("创建缓存文件{}失败", lastSyncTimeFile, e);
                return null;
            }
        } else {
            lastSyncTime = loadLastSyncTime(lastSyncTimeFile);
            if (lastSyncTime == null) {
                try {
                    lastSyncTime = FORMATTER.parse("1970-01-01 00:00:00");
                    // 如果读取失败，写入默认时间
                    saveLastSyncTime(lastSyncTime, lastSyncTimeFile);
                } catch (Exception e) {
                    log.error("转换缓存时间失败", e);
                }
            }
        }
        return lastSyncTime;
    }

    /**
     * 从文件中读取上次同步时间
     *
     * @return
     */
    Date loadLastSyncTime(String lastSyncTimeFile) {
        try (BufferedReader reader = new BufferedReader(new FileReader(lastSyncTimeFile))) {
            String timeStr = reader.readLine();
            if (timeStr != null && !timeStr.isEmpty()) {
                return FORMATTER.parse(timeStr);
            }
        } catch (Exception e) {
            log.warn("Could not load last sync time, using default", e);
        }
        return null;
    }

    /**
     * 将上次同步时间保存到文件
     *
     * @param time
     * @param lastSyncTimeFile
     */
    void saveLastSyncTime(Date time, String lastSyncTimeFile) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(lastSyncTimeFile))) {
            writer.write(FORMATTER.format(time));
        } catch (IOException e) {
            log.error("Failed to save last sync time", e);
        }
    }

    /**
     * 同步数据
     *
     * @param sourceJdbcTemplate
     * @param targetJdbcTemplate
     * @param lastSyncTimeFile
     * @return
     */
    Integer syncData(JdbcTemplate sourceJdbcTemplate, JdbcTemplate targetJdbcTemplate, String lastSyncTimeFile) {
        try {
            Date lastSyncTime = loadLastSyncTime(lastSyncTimeFile);
            // 1. 查询 source.message 表中 rksj >= lastSyncTime 的记录
            List<Message> newMessages = sourceJdbcTemplate.query(
                    "SELECT bh, content, ly, rksj, ip FROM message WHERE rksj >= ? ORDER BY rksj",
                    new Object[]{lastSyncTime},
                    new BeanPropertyRowMapper<>(Message.class)
            );

            // 2. 如果有新数据，批量插入到 target.cnyw 表
            if (!newMessages.isEmpty()) {
                String insertSql = "INSERT IGNORE INTO cnyw (bh, content, ly, rksj, ip) VALUES (?, ?, ?, ?, ?)";
                targetJdbcTemplate.batchUpdate(insertSql, newMessages, newMessages.size(),
                        (ps, message) -> {
                            log.info("同步数据bh{},content={},rksj={}", message.getBh(), message.getContent(), message.getRksj());
                            ps.setString(1, message.getBh());
                            ps.setString(2, message.getContent());
                            ps.setString(3, message.getLy());
                            ps.setObject(4, message.getRksj());
                            ps.setString(5, message.getIp());
                        });

                // 3. 更新 lastSyncTime 为本次查询的最大 rksj
                Date maxRksj = lastSyncTime;
                for (Message message : newMessages) {
                    if (message.getRksj().after(maxRksj)) {
                        maxRksj = message.getRksj();
                    }
                }
                lastSyncTime = maxRksj;
                // 持久化保存
                saveLastSyncTime(lastSyncTime, lastSyncTimeFile);
                log.info("同步数据量： {},更新同步时间： {}", newMessages.size(), FORMATTER.format(lastSyncTime));
                return newMessages.size();
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("同步出错", e);
            return -1;
        }
    }
}
